/**
 * 
 */
package scriptrunner.execution;

import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;

import scriptrunner.execution.parameter.Parameter;

/**
 * @author Administrator
 * 
 */
public class Session implements Serializable {

	// ///////////////////////////////////////////////////////////

	/**
	 * 
	 */
	private static final long serialVersionUID = 2522320465202898181L;

	public Session(Parameter<String> httpParameter) {
		this.httpParameter = httpParameter;
	}

	public void setHttpParameter(Parameter<String> httpParameter) {
		this.httpParameter = httpParameter;
	}

	public Parameter<String> getHttpParameter() {
		return httpParameter;
	}

	// ///////////////////////////////////////////////////////////////
	
	public void setVariableValueAsReference(String id, ValueObject value) {
		variableMap.put(id, value);
	}

	public void setVariableValue(String id, ValueObject value)
			throws ExecuteErrorException {
		try {
			variableMap.put(id, value.clone());
		} catch (CloneNotSupportedException e) {
			throw new ExecuteErrorException(
					"The value cannot be cloned when it is assigned to a varible");
		}
	}

	public ValueObject getVariableValue(String id) {
		return variableMap.get(id);
	}

	public void setReturnResult(ValueObject result) {
		this.result = result;
	}

	public ValueObject getReturnResult() {
		return result;
	}

	public ValueObject getHTTPVal(ValueObject idx) throws ExecuteErrorException {
		if (!(idx instanceof ValueStringObject))
			throw new ExecuteErrorException(
					"The index of HTTP variable should be a string");
		String idxString = ((ValueStringObject) idx).GetValue();
		return ConvertHTTPStringToValueObject(httpParameter
				.getParameterValue(idxString));
	}

	private ValueObject ConvertHTTPStringToValueObject(String s)
			throws ExecuteErrorException {
		if (s == null)
			throw new ExecuteErrorException("The HTTP string is null");

		// Integer
		try {
			int intValue = Integer.parseInt(s);
			return new ValueIntegerObject(intValue);
		} catch (NumberFormatException e) {
		}

		// Float
		try {
			float floatValue = Float.parseFloat(s);
			return new ValueFloatObject(floatValue);
		} catch (NumberFormatException e) {
		}

		// String
		return new ValueStringObject(s);
	}

	/*
	 * Discard the old values, update the session with the given one.
	 */
	public void sync(Session updatedSession) {
		this.variableMap = updatedSession.variableMap;
		this.result = updatedSession.result;
	}

	protected ValueObject result;
	protected Map<String, ValueObject> variableMap = new TreeMap<String, ValueObject>();
	Parameter<String> httpParameter;
}
